<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/10/19
 * Time: 15:18
 */

namespace app\api\controller;

use app\api\model\Weixin;
use app\common\model\Member;
use think\Cache;
use think\Controller;

use think\Request;
use Org\Wechat;
use Think\Config;
use app\common\controller\WechatController;
use app\common\controller\UtilController;

class OpenController extends Controller
{
    private static $Wechat ;
    private $frontUrl = "http://192.168.104.47:9000";
    function _initialize()
    {
        $hostName = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST']."/api/open";
        $this::$Wechat = new WechatController($this->frontUrl);
        $this::$Wechat->app_id = Config::get("wechat.app_id");
        $this::$Wechat->app_secret = Config::get("wechat.app_secret");
        $this::$Wechat->redirect_uri = $hostName;
    }

    function Index(){
        if ($code = Request::instance()->get('code')){
            $token = $this::$Wechat->get_access_token($code);
            $access_token = $token['access_token'];
            $refresh_token = $token['refresh_token'];
            $openid = $token['openid'];
            $User = $this->UserByOpenId($openid);
            if ($User){
                $Auth = new AuthController();
                $token = uniqid();
                $arr = [
                    'uid'=> $User['id'],
                    'openid' => $openid
                ];
                Cache::set($token, $arr,3600);
                return redirect($this->frontUrl."/completion.html?token=".$token);
            }else{
                return redirect($this->frontUrl."/question.html?openid=".$openid);
            }
        }else{
            return redirect($this::$Wechat->get_authorize_url(true));
        }
    }

    function actionBind(){
        if ($action = Request::instance()->get('action') && $openid = Request::instance()->get('openid') && $token = Request::instance()->get('token') ){
            switch ($action){
                case "bindwechat":
                    $CacheData = Cache::get($token);
                    break;
                case "unbindwechat":
                    //openid uid
                    break;
                default:
                    break;
            }
        }
    }

    //跳转到该地址   http://api.ch-jht.com/api/open/bindwechat?token=xxxxxx
    function BindWechat(){
        if ($code = Request::instance()->get('code')) {
            $WechatToken = $this::$Wechat->get_access_token($code);
            $openid = $WechatToken['openid'];
            $token = Request::instance()->get('token');
            if ($tokenData = Cache::get($token)){
                $model = new Member();
                $save_res = $model->save(['openid'=>$openid],['id'=>$tokenData['uid']]);
                return redirect($this->frontUrl."/completion.html?token=".$token."&success=".$save_res);
            }
        }else{
            if ($tokenData = Cache::get(Request::instance()->get('token'))) {
                $this::$Wechat->redirect_uri = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST']."/api/open/bindwechat?token=".Request::instance()->get('token');
                return redirect($this::$Wechat->get_authorize_url(true));
            }else{
               $token = Request::instance()->get('token');
               die(json_encode($token));
            }
        }
    }

    function UnBindWechat(){
        if ($tokenData = Cache::get(Request::instance()->get('token'))) {
            $model = new Member();
            $save_res = $model->save(['openid'=>''],['id'=>$tokenData['uid']]);
            if ($save_res){
                return UtilController::jsonResponse(['Success'=>true,'Msg'=>'解绑成功','Data'=>[]]);
            }else{
                return UtilController::jsonResponse(['Success'=>false,'Msg'=>'解绑失败','Data'=>[]]);
            }
        }
    }

    private function UserByOpenId($openid){
        $model = new Member();
        $res = $model->where('openid', $openid)->find();
        if ($res){
            return $res->toArray();
        }else{
            return false;
        }
    }


    function test(){
        Cache::set("token",[
            'uid' => 123,
        ]);
        var_dump(Cache::get("token"));
    }
}